package com.jiufengxinxi.ts.init;

import com.jiufengxinxi.ts.web.controller.LoginController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author stydm
 * @className InitBusiness
 * @description 业务初始化
 * @date 2020/7/9 10:52
 */

@Component
@Order(2)
public class InitBusiness implements CommandLineRunner {

    private static final Logger logger =  LoggerFactory.getLogger(LoginController.class);

    @Override
    public void run(String... args) throws Exception {
        logger.info("!----------------- 业务开始初始化 -----------------!");
        download("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3015419982,3461204405&fm=15&gp=0.jpg","12312312.jpg","D:\\\\image\\\\");
        logger.info("!----------------- 业务初始化成功 -----------------!");
    }


    /**
    * @description  : 下载图片类
    * @author: stydm
    * @date: 2020/7/10 16:56
    * @param urlString urld
    * @param filename sdfsd
    * @param savePath sdfsdfs
    * @return: void
    */
    public static void download(String urlString, String filename,String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
        //设置请求超时为5s
        con.setConnectTimeout(5*1000);
        // 输入流
        InputStream is = con.getInputStream();

        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        File sf=new File(savePath);
        if(!sf.exists()){
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        // 完毕，关闭所有链接
        os.close();
        is.close();
    }
}
